#include <stdio.h>
#include <unistd.h>
#include <string.h>

#include "iot_gpio_ex.h"
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_uart.h"
#include "hi_uart.h"
#include "iot_watchdog.h"
#include "iot_errno.h"
#include "iot_i2c.h"
#include "hi_errno.h"
#include "hi_i2c.h"
#include "oled_ssd1306.h"
#include "ohos_init.h"
#include "hi_timer.h"


#define UART_BUFF_SIZE 100
#define U_SLEEP_TIME   100000
#define DELAY_MS    1000
#define NUM         1
#define STACK_SIZE  1024
#define IOT_I2C_IDX_BAUDRATE (400 * 1000)
#define CW2015_I2C_IDX 0
#define CW2015_READ_ADDR     (0xC5)
#define CW2015_WRITE_ADDR    (0xC4)
#define DELAY_US    20
#define PARKING_CAPACITY 2
#define IOT_PWM_PORT_PWM3   3
#define WRITELEN  2
#define CW2015_HIGHT_REGISTER 0x02
#define CW2015_LOW_REGISTER   0x03
#define CW2015_WAKE_REGISTER  0x0A
#define DELYA_US20            20

// 添加NFC检测状态变量
static int nfc_detected = 0;

uint32_t Cw20_WriteRead(uint8_t reg_high_8bit_cmd, uint8_t send_len, uint8_t read_len)
{
    uint32_t status = 0;
    uint32_t ret = 0;
    uint8_t recvData[888] = { 0 };
    hi_i2c_data i2c_write_cmd_addr = { 0 };
    uint8_t send_user_cmd[1] = {reg_high_8bit_cmd};
    memset(recvData, 0x0, sizeof(recvData));
    i2c_write_cmd_addr.send_buf = send_user_cmd;
    i2c_write_cmd_addr.send_len = send_len;

    i2c_write_cmd_addr.receive_buf = recvData;
    i2c_write_cmd_addr.receive_len = read_len;

    status = hi_i2c_writeread(CW2015_I2C_IDX, CW2015_READ_ADDR, &i2c_write_cmd_addr);
    if (status != IOT_SUCCESS) {
        printf("I2cRead() failed, %0X!\n", status);
        return status;
    }
    ret = recvData[0];
    return ret;
}

uint32_t Cw20_Write(uint8_t addr, uint8_t writedata, uint32_t buffLen)
{
    uint8_t buffer[2] = {addr, writedata};
    uint32_t retval = IoTI2cWrite(CW2015_I2C_IDX, CW2015_WRITE_ADDR, buffer, buffLen);
    if (retval != IOT_SUCCESS) {
        printf("IoTI2cWrite(%02X) failed, %0X!\n", buffer[0], retval);
        return retval;
    }
    printf("IoTI2cWrite(%02X)\r\n", buffer[0]);
    return IOT_SUCCESS;
}

void CW2015Init(void)
{
    IoTI2cInit(CW2015_I2C_IDX, IOT_I2C_IDX_BAUDRATE);
    IoTI2cSetBaudrate(CW2015_I2C_IDX, IOT_I2C_IDX_BAUDRATE);
    IoSetFunc(IOT_IO_NAME_GPIO_13, IOT_IO_FUNC_GPIO_13_I2C0_SDA);
    IoSetFunc(IOT_IO_NAME_GPIO_14, IOT_IO_FUNC_GPIO_14_I2C0_SCL);
    Cw20_Write(CW2015_WAKE_REGISTER, 0x00, 2);
}

// 初始化OLED显示
void InitOLED()
{
    CW2015Init();
    OledInit();
    OledFillScreen(0);
}

// 显示BOOK ID
void DisplayBookID()
{
    OledFillScreen(0);
    OledShowString(20, 4, "BOOK ID", 1);
    OledShowString(20, 5, "01", 1);
}

// 显示欢迎信息
void DisplayWelcome()
{
    OledFillScreen(0);
    OledShowString(20, 4, "WELCOME", 1);
}

void Uart1GpioInit(void)
{
    IoTGpioInit(IOT_IO_NAME_GPIO_0);
    IoSetFunc(IOT_IO_NAME_GPIO_0, IOT_IO_FUNC_GPIO_0_UART1_TXD);
    IoTGpioInit(IOT_IO_NAME_GPIO_1);
    IoSetFunc(IOT_IO_NAME_GPIO_1, IOT_IO_FUNC_GPIO_1_UART1_RXD);
}

void Uart1Config(void)
{
    uint32_t ret;
    IotUartAttribute uart_attr = {
        .baudRate = 9600,
        .dataBits = 8,
        .stopBits = 1,
        .parity = 0,
    };
    ret = IoTUartInit(HI_UART_IDX_1, &uart_attr);
    if (ret != IOT_SUCCESS) {
        printf("Init Uart1 Failed Error No : %d\n", ret);
        return;
    }
}

static void UartTask(void)
{
    const char *data = "Hello OpenHarmony !!!\n";
    uint32_t len = 0;
    unsigned char uartReadBuff[UART_BUFF_SIZE] = {0};
    uint32_t last_nfc_time = 0; // 记录上次检测到NFC的时间

    Uart1GpioInit();
    Uart1Config();

    // 初始显示欢迎信息
    DisplayWelcome();

    while (1) {
        IoTUartWrite(HI_UART_IDX_1, (unsigned char*)data, strlen(data));
        
        // 读取串口数据
        len = IoTUartRead(HI_UART_IDX_1, uartReadBuff, UART_BUFF_SIZE);
        if (len > 0) {
            // 检测到NFC数据
            nfc_detected = 1;
            last_nfc_time = hi_get_milli_seconds(); // 记录当前时间
            printf("NFC detected! Book ID: 01\n");
            DisplayBookID(); // 显示BOOK ID
        } else {
            // 检查NFC超时（1秒内没有检测到新数据）
            if (nfc_detected && (hi_get_milli_seconds() - last_nfc_time > 1000)) {
                nfc_detected = 0;
                printf("NFC not detected. Displaying welcome.\n");
                DisplayWelcome(); // 显示欢迎信息
            }
        }
        
        usleep(U_SLEEP_TIME);
    }
}

void UartExampleEntry(void)
{
    osThreadAttr_t attr;
    InitOLED();
    IoTWatchDogDisable();

    attr.name = "UartTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 5 * 1024;
    attr.priority = osPriorityNormal;

    if (osThreadNew((osThreadFunc_t)UartTask, NULL, &attr) == NULL) {
        printf("[UartTask] Failed to create UartTask!\n");
    }
}

APP_FEATURE_INIT(UartExampleEntry);